<template>
  <view class="content pt-30 pb-50 pl-20 pr-20">
    <view class="detail-block pd-20">
      <view class="mb-20" style="display: flex;">
        <view class="title-block">问题描述</view>
      </view>
      <view>
        <textarea class="text-area pd-20" placeholder="请输入问题描述" placeholder-class="placeholder" v-model="params.description"></textarea>
      </view>
    </view>
    <view class="form-block pl-20 pr-20">
      <view class="pt-20" style="display: flex;">
        <view class="title-block">上报信息</view>
      </view>
      <view class="item-block pt-20 pb-20 border-b-common">
        <view class="item-label"><text class="wraning-icon">*</text>问题所属单位</view>
        <view class="item-select" @click="routeByUrl('/pagesCommon/departmentList?paramsKey=beCheck&departmentState=1')">
          <text v-if="params.beCheckDeptIdName" class="mr-10">{{params.beCheckDeptIdName}}</text>
          <text v-else class="item-default-text mr-10">请选择问题所属单位</text>
          <u-icon name="arrow-right" size="26rpx" color="#CCCCCC"></u-icon>
        </view>
      </view>
      <view class="item-block pt-20 pb-20 border-b-common">
        <view class="item-label"><text class="wraning-icon">*</text>所在位置</view>
        <view class="item-select">
          <input class="item-input text-r" style="width: 600rpx; max-width: 600rpx;" placeholder="请输入/选择所在位置" placeholder-class="placeholder" v-model="params.place" />
          <u-icon name="map" size="40rpx" color="#3F99F7" @click="getLocationInfo()"></u-icon>
        </view>
      </view>
      <view class="item-block pt-20 pb-20 border-b-common">
        <view class="item-label"><text class="wraning-icon">*</text>问题照片</view>
        <view class="image-list">
          <u-upload :action="action" multiple :max-count="3" :file-list="fileList" @afterRead="afterRead" @delete="deleteImage"></u-upload>
        </view>
      </view>
      <view class="item-block pt-20 pb-20 border-b-common">
        <view class="item-label"><text class="wraning-icon">*</text>隐患等级</view>
        <view class="item-select" @click="() => levelState = true">
          <text v-if="params.levelName" class="mr-10">{{params.levelName}}</text>
          <text v-else class="item-default-text mr-10">请选择隐患等级</text>
          <u-icon name="arrow-right" size="26rpx" color="#CCCCCC"></u-icon>
        </view>
      </view>
      <view class="item-block pt-20 pb-20 border-b-common">
        <view class="item-label"><text class="wraning-icon">*</text>上报单位</view>
        <view class="item-select">
          <text v-if="params.checkDeptIdName" class="mr-10">{{params.checkDeptIdName}}</text>
          <text v-else class="item-default-text mr-10">请选择上报单位</text>
          <u-icon name="arrow-right" size="26rpx" color="#CCCCCC"></u-icon>
        </view>
      </view>
      <view class="item-block pt-20 pb-20">
        <view class="item-label"><text class="wraning-icon">*</text>上报人</view>
        <view class="item-select">
          <text v-if="params.checkPeoIdName" class="mr-10">{{params.checkPeoIdName}}</text>
          <text v-else class="item-default-text mr-10">请选择上报人</text>
          <u-icon name="arrow-right" size="26rpx" color="#CCCCCC"></u-icon>
        </view>
      </view>
    </view>
    <view class="button-block mt-30">
      <button class="button-submit" style="width: 600rpx;" @click="$u.throttle(submit, 1000)">提交</button>
    </view>
    <u-picker :show="levelState" :columns="levelList" keyName="label" @confirm="pickerConfirm('level', $event)" @cancel="pickerCancel('level')"></u-picker>
  </view>
</template>

<script>
  import { creatDangerInfoApi } from '@/apis/danger/index.js'
  import { getHtLevelDictListApi } from '@/apis/danger/common.js'
  import { getToken, getUserInfo } from '@/utils/auth.js'
  
  export default {
    data() {
      return {
        action: this.uploadImageUrl,
        fileList: [],
        params: {
          source: 0,
          description: '',
          beCheckDeptId: '',
          beCheckDeptIdName: '',
          place: '',
          ossImg: [],
          checkDeptIdName: '',
          checkDeptId: '',
          checkPeoIdName: '',
          checkPeoId: '',
          level: '',
          levelName: ''
        },
        levelState: false,
        levelList: [],
      }
    },
    onLoad() {
      if(getUserInfo()) {
        let userInfo = getUserInfo()
        Object.assign(this.params, {
          checkDeptId: userInfo.dept.id,
          checkDeptIdName: userInfo.dept.name,
          checkPeoId: userInfo.id,
          checkPeoIdName: userInfo.nickname,
          beCheckDeptId: userInfo.dept.id,
          beCheckDeptIdName: userInfo.dept.name,
        })
      }
      this.getHtLevelDictList()
    },
    methods: {
      submit: function() {
        if(!this.authFormData()) return false
        let params = JSON.parse(JSON.stringify(this.params))
        creatDangerInfoApi(params).then(res => {
          uni.showToast({ title: '随手拍提交成功', icon: 'none' })
          setTimeout(() => uni.navigateBack(), 500)
        }).catch(err => console.warn(err))
      },
      getLocationInfo: function() {
        uni.getLocation({
          geocode: true,
          success: res => {
            uni.chooseLocation({
              latitude: res.latitude,
              longitude: res.longitude,
              success: result => {
                this.params.place = result.name
              }
            })
          }
        })
      },
      getHtLevelDictList: function() {
        getHtLevelDictListApi().then(res => {
          res.map(item => {
            if(item.value == '2') {
              this.params.level = item.value
              this.params.levelName = item.label
            }
          })
          this.levelList = [res]
        }).catch(err => console.warn(err))
      },
      pickerConfirm: function(type, event) {
        this.params[type] = event.value[0].value
        this.params[`${type}Name`] = event.value[0].label
        this[`${type}State`] = false
      },
      pickerCancel: function(type) {
        this[`${type}State`] = false
      },
      async afterRead(event) {
        // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
        let lists = [].concat(event.file)
        let fileListLen = this.fileList.length
        lists.map((item) => {
          this.fileList.push({
            ...item,
            status: 'uploading',
            message: '上传中'
          })
        })
        for (let i = 0; i < lists.length; i++) {
          const result = await this.uploadFilePromise(lists[i].url)
          let item = this.fileList[fileListLen]
          if(result.status == 'success') {
            this.fileList.splice(fileListLen, 1, Object.assign(item, {
              status: result.status,
              message: '',
              url: result.url
            }))
            fileListLen++
          } else {
            this.fileList.splice(fileListLen, 1)
          }
        }
      },
      uploadFilePromise(url) {
        return new Promise((resolve, reject) => {
          let a = uni.uploadFile({
            url: this.uploadImageUrl,
            filePath: url,
            name: 'file',
            formData: {
              user: 'test'
            },
            header: {
              'Authorization': `Bearer ${getToken()}`,
              'tenant-id':  '1'
            },
            success: (res) => {
              let result = JSON.parse(res.data)
              if (result.code == 0) {
                this.params.ossImg.push(result.data)
                resolve({url: result.data.url, status: 'success'})
              } else {
                uni.showToast({ title: 'OSS服务器错误', icon: 'none' })
                resolve({url, status: 'fail'})
              }
            },
            fail: () => uni.showToast({ title: '图片上传失败', icon: 'none' })
          })
        })
      },
      deleteImage(event) {
        this.params
        this.fileList.splice(event.index, 1)
      },
      routeByUrl: function(url) {
        uni.navigateTo({ url })
      },
      authFormData: function() {
        let params = this.params
        if(!params.description) {
          uni.showToast({ title: '请输入问题描述', icon: 'none' })
          return false
        }
        if(!params.beCheckDeptIdName) {
          uni.showToast({ title: '请选择问题所属单位', icon: 'none' })
          return false
        }
        if(!params.place) {
          uni.showToast({ title: '请输入/选择所在位置', icon: 'none' })
          return false
        }
        if(params.ossImg.length <= 0) {
          uni.showToast({ title: '请上传至少一张问题照片', icon: 'none' })
          return false
        }
        if(!params.checkDeptIdName) {
          uni.showToast({ title: '请选择上报单位', icon: 'none' })
          return false
        }
        if(!params.checkPeoIdName) {
          uni.showToast({ title: '请选择上报人', icon: 'none' })
          return false
        }
        return true
      }
    }
  }
</script>

<style>
  page {
    background-color: #F4F4F4;
  }
</style>

<style lang="scss" scoped>
  .content {
    .detail-block {
      border-radius: 6rpx;
      background-color: #FFFFFF;
      .title-block {
        font-size: 30rpx;
        line-height: 42rpx;
        color: #222222;
        font-weight: 500;
        background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0) 50%, #C5DBFF 50%, #C5DBFF);
      }
      .item-block {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .item-label {
          font-size: 28rpx;
          line-height: 40rpx;
          color: #333333;
          .wraning-icon {
            color: #FE0303;
            margin-right: 5rpx;
          }
        }
        .item-value {
          font-size: 28rpx;
          line-height: 40rpx;
          color: #999999;
          max-width: 500rpx;
          display: flex;
          align-items: center;
        }
        .image-list {
          max-width: 520rpx;
          display: flex;
          justify-content: flex-end;
          flex-direction: row-reverse;
          flex-wrap: wrap;
          .image {
            width: 156rpx;
            height: 120rpx;
            border-radius: 6rpx;
            background-color: #CCCCCC;
            margin-left: 20rpx;
            margin-bottom: 20rpx;
          }
          .image:nth-child(3n) {
            margin-left: 0;
          }
        }
      }
      .text-area {
        width: 630rpx;
        height: 300rpx;
        font-size: 28rpx;
        line-height: 40rpx;
        color: #333333;
        border: 1rpx solid #EEEEEE;
        border-radius: 6rpx;
      }
      .placeholder {
        font-size: 28rpx;
        line-height: 40rpx;
        color: #999999;
      }
    }
    .text-over {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .form-block {
      border-radius: 6rpx;
      background-color: #FFFFFF;
      .title-block {
        font-size: 30rpx;
        line-height: 42rpx;
        color: #222222;
        font-weight: 500;
        background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0) 50%, #C5DBFF 50%, #C5DBFF);
      }
      .item-block {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .item-label {
          font-size: 28rpx;
          line-height: 40rpx;
          color: #333333;
          .wraning-icon {
            color: #FE0303;
            margin-right: 5rpx;
          }
        }
        .item-input {
          max-width: 420rpx;
          font-size: 28rpx;
          line-height: 40rpx;
          color: #333333;
        }
        .placeholder {
          font-size: 28rpx;
          line-height: 40rpx;
          color: #999999;
        }
        .item-select {
          max-width: 420rpx;
          display: flex;
          align-items: center;
          font-size: 28rpx;
          line-height: 40rpx;
          color: #333333;
          .item-default-text {
            color: #999999;
          }
        }
        .image-list {
          max-width: 530rpx;
        }
      }
    }
    .button-block {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .button-cancel {
        width: 334rpx;
        height: 80rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 26rpx;
        color: #FFFFFF;
        border-radius: 8rpx;
        background-color: #BBBBBB;
      }
      .button-cancel::after {
        border: none
      }
      .button-submit {
        @extend .button-cancel;
        background-color: #3F99F7;
      }
      .button-submit::after {
        border: none;
      }
    }
  }
</style>